using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Crm.SdkTypeProxy.Metadata;

namespace winCRM4QueryBuilder
{
   public class CrmServiceUtility
    {
       public static CrmService GetCrmService()
      {
         return GetCrmService(null, null);
      }

      public static CrmService GetCrmService(string organizationName)
      {
         return GetCrmService(null, organizationName);
      }

      /// <summary>
      /// Set up the CRM Service.
      /// </summary>
      /// <param name="organizationName">My Organization</param>
      /// <returns>CrmService configured with AD Authentication</returns>
      public static CrmService GetCrmService(string crmServerUrl, string organizationName)
      {
         // Get the CRM Users appointments
         // Setup the Authentication Token
         CrmAuthenticationToken token = new CrmAuthenticationToken();
         token.OrganizationName = organizationName;
      
         CrmService service = new CrmService();

         if (crmServerUrl != null &&
            crmServerUrl.Length > 0)
         {
            UriBuilder builder = new UriBuilder(crmServerUrl);            
            builder.Path = "//MSCRMServices//2007//CrmService.asmx";
            service.Url = builder.Uri.ToString();
         }

         service.Credentials = System.Net.CredentialCache.DefaultCredentials;
         service.CrmAuthenticationTokenValue = token;

         return service;
      }

      /// <summary>
      /// Set up the CRM Metadata Service.
      /// </summary>
      /// <param name="organizationName">My Organization</param>
      /// <returns>MetadataService configured with AD Authentication</returns>
      public static MetadataService GetMetadataService(string crmServerUrl, string organizationName)
      {
         // Get the CRM Users appointments
         // Setup the Authentication Token
         CrmAuthenticationToken token = new CrmAuthenticationToken();
         token.OrganizationName = organizationName;

         MetadataService service = new MetadataService();

         if (crmServerUrl != null &&
            crmServerUrl.Length > 0)
         {
            UriBuilder builder = new UriBuilder(crmServerUrl);            
            builder.Path = "//MSCRMServices//2007//MetadataService.asmx";
            service.Url = builder.Uri.ToString();
         }
         
         service.Credentials = System.Net.CredentialCache.DefaultCredentials;
         service.CrmAuthenticationTokenValue = token;

         return service;
      }
    }
}
